public class Test04 {
    public static int replace(char[] string,int oldlength){
        if(string == null || string.length == 0){
            return -1;
        }
        int count = 0;//统计空格的个数
        for(int i = 0; i<string.length;i++){
            if(string[i] == ' ') count ++;
        }
        if (count == 0) return oldlength; //如果空格数为0，则返回原来的长度
        int targetlength = oldlength + count*2;
        if(targetlength > string.length){//如果转换后的长度，大于数组的最大长度直接返回失败
            return -1;
        }
        int temp = targetlength;
        oldlength --;
        targetlength --;
        while(oldlength >= 0 && targetlength>oldlength){
            if (string[oldlength] == ' '){
                string[targetlength--] ='0';
                string[targetlength--] ='2';
                string[targetlength--]='%';
            }else
                string[targetlength--]=string[oldlength];
            oldlength --;
        }
        return temp;
    }

    public static void main(String[] args) {
        char[] string = new char[50];
        string[0] = ' ';
        string[1] = 'e';
        string[2] = ' ';
        string[3] = ' ';
        string[4] = 'r';
        string[5] = 'e';
        string[6] = ' ';
        string[7] = ' ';
        string[8] = 'a';
        string[9] = ' ';
        string[10] = 'p';
        string[11] = ' ';

        int length = replace(string,12);
        System.out.println(new String(string, 0, length));
    }
}
